﻿/**
 * 全局应用程序对象
 */
var app = new (class Application {
    constructor() {
        this.loading = new Map();
        this.loaded = new Map();
        this.config = _config_;
        this.cache = localCache;
        this.alert = swal;
        this.cache.debug = _config_.debug;
        //$.alert = $('#__ModalAlertTemplate').children().alert().data(_config_.alert.namespace);
        //_config_.debug = true;
    }

    init() {
        //$.ajaxSetup({
        //    beforeSend: function (xhr) {
        //        xhr._startTime = new Date();
        //    },
        //    complete: function (xhr) {
        //        $.com.ajaxComplete(this, xhr);
        //    }
        //});

        //处理全局 kendo ui 组件语言为中文
        kendo.culture('zh-CN');
        //用于处理全局验证消息显示位置问题
        kendo.ui.validator.messageLocators = {
            custom: {
                locate: function (e, name) {
                    return e.parents(_config_.selector.inputFormGroup).find(_config_.selector.inputInvalidMsg);
                },
                decorate: function (a, b) {
                    //return a;
                }
            }
        };

        //初始化组件
        var $showbox = $(_config_.selector.showbox);
        if ($.com.isJqueryObject($showbox)) {
            $showbox.showbox();
        }
        //现在修改为每次只初始化顶级form, 并且每级form都必须配field属性, 为了自动产生id
        var $forms = $(_config_.selector.form);
        if ($.com.isJqueryObject($forms)) {
            $forms.each((index, element) => {
                var $form = $(element);
                if ((!$.com.isJqueryObject($form.parents(_config_.selector.form)) && !($.com.isJqueryObject($form.parents(_config_.selector.notForm)))) || $form.is(_config_.selector.autoStartup)) {
                    $form.form();
                }
            });
        }

        $(_config_.selector.grid).grid();
        $(_config_.selector.popupWindow).popupWindow();
        $(_config_.selector.popup).not(_config_.selector.field).popup();

        //处理高级查询按钮
        var $advancedSearch = $('[data-button="advancedSearch"]');
        window.onresize = function (event) {
            $.com.resizeAdvancedSearch($advancedSearch);
            event.stopPropagation();
        };

        $.com.advancedSearchColorful($advancedSearch);
    }

    startup() {
        return Promise.resolve()
            .then(() => localCache.load())
            .then(() => this.execute(this.loading))
            .then(this.init)
            .then(() => this.execute(this.loaded))
            .catch(error => this.error(error));
    }

    execute(funs) {
        let promise = Promise.resolve();
        if (funs.size > 0) {
            funs = funs.toArray().sort((x, y) => x.key <= y.key).toMap();
        }

        funs.forEach(fun => promise = promise.then(() => fun()));
        return promise;
    }

    info(text, options) {
        if (_config_.debug) {
            console.info(text);
        }

        return this.alert($.extend({
            icon: "info",
            text: text,
            timer: 5000,
            button: {
                text: "确 定",
                value: true,
                visible: true,
                closeModal: true,
            }
        }, options));
    }

    success(text, options) {
        if (_config_.debug) {
            console.log(text);
        }

        return this.alert($.extend({
            icon: "success",
            text: text,
            closeOnEsc: false,
            closeOnClickOutside: false,
            button: {
                text: "确 定",
                value: true,
                visible: true,
                closeModal: true,
            }
        }, options));
    }

    error(text, options) {
        if (_config_.debug) {
            console.error(text);
        }

        if (typeof text !== "string") {
            text = (text instanceof Error) ? text.message : text.toString();
        }

        return this.alert($.extend({
            icon: "error",
            text: text,
            closeOnEsc: false,
            closeOnClickOutside: false,
            button: {
                text: "确 定",
                className: "swal-button--danger",
                value: true,
                visible: true,
                closeModal: true,
            }
        }, options));
    }

    warning(text, options) {
        if (_config_.debug) {
            console.warn(text);
        }

        return this.alert($.extend({
            icon: "warning",
            text: text,
            closeOnEsc: false,
            closeOnClickOutside: false,
            button: {
                text: "确 定",
                className: "swal-button--warning",
                value: true,
                visible: true,
                closeModal: true,
            }
        }, options));
    }

    question(text, options) {
        if (_config_.debug) {
            console.info(text);
        }

        let alert = this.alert($.extend({
            icon: "warning",
            text: text,
            //content: $('#__TemplateAlert').children()[0],
            dangerMode: true,
            closeOnEsc: false,
            closeOnClickOutside: false,
            buttons: {
                cancel: {
                    text: "取 消",
                    value: false,
                    visible: true,
                    closeModal: true,
                },
                confirm: {
                    text: "确 定",
                    value: true,
                    visible: true,
                    closeModal: true
                }
            }
        }, options));

        $('.swal-modal .swal-icon').empty().append('<i class="question fa fa-question fa-5x"></i>');
        return alert;
    }

    /**
     * 来自 /api/Attachments 接口的文件下载功能
     * @param {any} filePath 文件路径
     * @param {any} fileName 下载文件名
     */
    download(filePath, fileName) {
        var url = `/api/Attachments/Download?fileName=${fileName}`
        if ($.com.hasValue(filePath)) {
            url += `&filePath=${filePath}`;
        }

        if ($.com.isIE()) {
            url = encodeURI(url);
        }

        return fetch(url,
            {
                headers: {
                    "Accept": "application/json; charset=utf-8",
                    "Content-Type": "application/octet-stream"
                },
                credentials: 'include'
            })
            .then(x => {
                if (x.ok) {
                    if (!$.com.hasValue(fileName)) {
                        //服务器端使用了 url 编码
                        fileName = decodeURI(x.headers.get('fileName'));
                    }

                    return x.blob().then(x => download(x, fileName));
                }
            });
    }
})();
